﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Coding4Fun.MissionControl.WP.Network
{
    public class CommandClient
    {
        private SocketClient client;

        public Task<bool> SendCommand(string server, string key, string associatedValue, Action<bool> onCompleted = null)
        {
            var taskCompletionSource = new TaskCompletionSource<bool>();

            client = new SocketClient();
            client.OnClientConnected += (s, args) =>
            {
                if (args.IsSuccessful)
                {
                    string data = JsonConvert.SerializeObject(new KeyValuePair<string, string>(key, associatedValue));
                    client.Send(data);
                }

                taskCompletionSource.SetResult(args.IsSuccessful);
                client = null;
            };
            client.Connect(server, 6169);

            return taskCompletionSource.Task;
        }

        public void AbandonAttempt()
        {
            if (client != null)
                client.Cancel();
        }
    }
}
